package com.yanqu.road.server.webservice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.enums.activity.eActivityChargeType;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.language.LanguageType;
import com.yanqu.road.entity.log.LogPreRecharge;
import com.yanqu.road.entity.log.LogTriggerRMBMallPrecharge;
import com.yanqu.road.entity.player.*;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.entity.xiaomian.UserXiaoMianData;
import com.yanqu.road.logic.bussiness.player.UserAttributeBussiness;
import com.yanqu.road.logic.bussiness.player.UserBussiness;
import com.yanqu.road.logic.bussiness.player.UserCardBussiness;
import com.yanqu.road.logic.bussiness.player.UserTitleUpgradeBussiness;
import com.yanqu.road.logic.bussiness.xiaomian.XiaoMianBussiness;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.agent.AgentGeneral;
import com.yanqu.road.server.agent.AgentInterfaceMgr;
import com.yanqu.road.server.command.api.CmdMetaInfo;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.AttributeModule;
import com.yanqu.road.server.gameplayer.module.player.CardModule;
import com.yanqu.road.server.gameplayer.module.player.CouponModule;
import com.yanqu.road.server.gameplayer.module.player.PlayerModule;
import com.yanqu.road.server.gameplayer.module.xiaomian.XiaoMianModule;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.logic.platform.DeductIngotsManager;
import com.yanqu.road.server.logic.platform.ReduceItemManager;
import com.yanqu.road.server.logic.player.LoginIpManager;
import com.yanqu.road.server.logic.recharge.RechargeManager;
import com.yanqu.road.server.logic.recharge.limit.BaseRMBMallLimit;
import com.yanqu.road.server.logic.recharge.limit.MallLimitFactory;
import com.yanqu.road.server.manger.*;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.activity.RelationActivityMgr;
import com.yanqu.road.server.manger.activity.platform.PlatformActivityMgr;
import com.yanqu.road.server.manger.activity.platform.PlatformMailAntiActivityMgr;
import com.yanqu.road.server.manger.activity.unionwar.UnionWarActivityMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.MallMgr;
import com.yanqu.road.server.manger.config.MallRechargeConfigMgr;
import com.yanqu.road.server.manger.config.UnionConfigMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.monopolymarket.MonopolyMarketMgr;
import com.yanqu.road.server.manger.platform.PlatformUserBehaviorMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.PrivilegeCardMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.thirdparty.ThirdPartyMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.manger.union.UnionMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.jws.WebService;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.*;

@WebService
public class GameWebService {

    private static Logger logger = LogManager.getLogger(GameWebService.class.getName());

    /**
     * 方法名,参数-
     *
     * @param userId
     * @param commands
     * @return
     */
    public int executeAdminCommand(long userId, String commands) {
        try {
            Class<?> agentGeneral = AgentGeneral.class;
            Object invoke = agentGeneral.newInstance();
            String[] command = commands.split("-");
            for (int i = 0; i < command.length; i++) {
                String[] params = command[i].split(",");
                String methodStr = params[0];
                String param = "";
                if (params.length > 1) {
                    param = params[1];
                }

                Method method;
                try {
                    method = agentGeneral.getMethod(methodStr.trim(), new Class[]{long.class, String.class});
                } catch (Exception ex) {
                    continue;
                }
                method.invoke(invoke, new Object[]{userId, param.trim()});
            }

        } catch (Exception ex) {
            return -1;
        }
        return 0;
    }

    public String executeAdminOperate(String op, String param) {
        JSONObject ret = new JSONObject();
        ret.put("status", 0);
        ret.put("msg", "中心服务执行操作异常失败!!");
        if (!StringUtils.isNullOrEmpty(op)) {
            try {
                return AgentInterfaceMgr.executeAgentInterface(op, param);
            } catch (Exception ex) {
                logger.error("executeAdminOperate", ex);
                ex.printStackTrace();
            }
        }
        return ret.toString();
    }

    public int notifyRechargeSuccess(String orderNo, int rechargeType) {
        if(0 == rechargeType) {
            return RechargeManager.msgNotifyRechargeSuccess(orderNo);
        }else if(1 == rechargeType){
            return RechargeManager.msgNotifyThirdPartyRechargeSuccess(orderNo);
        }else if(2 == rechargeType){
            return RechargeManager.msgNotifyGoldTokenRechargeSuccess(orderNo);
        }
        return 0;
    }

    /**
     * 记录玩家登录ip
     */
    public void recordUserIp(long userId, String ip) {
        LoginIpManager.recordUserIp(userId, ip);
    }

    public void recordUserSign(long userId, String key, String value) {
        UserMgr.recordUserSignValue(userId, value);
    }

    /**
     * 记录预下单
     */
    public void logPreRecharge(long userId, String orderNo, int mallId) {
        MallInfo mallInfo = MallMgr.getMallInfoByMallId(mallId);
        if (mallInfo != null) {
            long price = MallRechargeConfigMgr.getPrice(mallInfo);
            AutoLogMgr.add(new LogPreRecharge(userId, mallId, orderNo, price));
            if (mallInfo.getShopType() == eShopType.RMBMallActivityMall.getValue()) {//现金礼包预下单
                AutoLogMgr.add(new LogTriggerRMBMallPrecharge(userId, mallInfo.getActivityId(), mallId, orderNo, price));
            }
        }
    }

    public String queryUser(String openId) {
        ServerInfo serverInfo = ServerListMgr.getServerInfo(GameServer.getInstance().getServerId());
        String serverName = serverInfo == null ? ("" + GameServer.getInstance().getServerId()) : serverInfo.getServerName();

        List<UserInfo> userInfoList = UserBussiness.getUserInfoList(openId);
        if (userInfoList.size() <= 0) {
            return "";
        }
        JSONObject dataObj = new JSONObject();
        JSONArray userObjArr = new JSONArray();
        for (UserInfo userInfo : userInfoList) {
            try {
                GamePlayer player = GamePlayerMgr.getOnlinePlayer(userInfo.getUserId());
                long ingots;
                if (null != player) {
                    ingots = player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.Ingots);
                } else {
                    UserAttribute userAttribute = UserAttributeBussiness.getUserAttribute(userInfo.getUserId(), ePlayerAttrType.Ingots);
                    if (userAttribute == null) {
                        ingots = 0;
                    } else {
                        ingots = userAttribute.getValue();
                    }
                }
                JSONObject userObj = new JSONObject();
                userObj.put("roleLevel", userInfo.getTitleId() + "");
                userObj.put("roleName", userInfo.getNickName());
                userObj.put("roleId", userInfo.getUserId() + "");
                userObj.put("roleCoin", ingots);
                userObj.put("earnSpeed", userInfo.getEarnSpeed().toString());
                userObj.put("serverName", serverName);
                userObj.put("phonePlatform", userInfo.getPhonePlatform());
                userObj.put("registerTime", userInfo.getRegisterTime());
                userObj.put("lastLoginTime", userInfo.getLastLoginTime());
                userObj.put("vipLv", VipMgr.getVipLv(userInfo.getVipExp()));
                userObj.put("platformUserId", userInfo.getPlatformUserId());
                userObjArr.add(userObj);
            } catch (Exception ex) {
                logger.error("异常 " + ex);
            }
        }
        dataObj.put("roleList", userObjArr);
        return dataObj.toJSONString();
    }

    public String queryUserUnionInfo(String platformUserId, long userId) {
        JSONObject resultObj = new JSONObject();
        UserInfo userInfo = UserMgr.getUserInfo(userId);
        if (userInfo == null) {
            return "";
        } else {
            if (!StringUtils.isNullOrEmpty(userInfo.getUnionUid())) {
                CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(userInfo.getUnionUid());
                if (unionInfo != null && CrossUnionMgr.getUnionMember(userId) != null) {
                    resultObj.put("unionUid", unionInfo.getUnionUid());
                    resultObj.put("unionName", unionInfo.getUnionName());
                    resultObj.put("serverId", unionInfo.getServerId());
                }
            }
        }
        return resultObj.toJSONString();
    }

    public String queryUnionDetailInfo(String unionUid) {
        JSONObject resultObj = new JSONObject();
        CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        if (unionInfo == null) {
            unionInfo = CrossUnionMgr.getDeleteUnionInfoMap().get(unionUid);
        }
        if (unionInfo == null) {
            return "";
        } else {

            resultObj.put("unionUid", unionInfo.getUnionUid());
            resultObj.put("unionName", unionInfo.getUnionName());
            resultObj.put("isDelete", unionInfo.isDelete() ? 1 : 0);
            resultObj.put("createTime", unionInfo.getCreateTime());
            resultObj.put("unionLv", UnionConfigMgr.getUnionLv(unionInfo.getExperience()));
            int crossServerCount = CrossUnionServerGroupMgr.getGroupServerCountByServerId(unionInfo.getServerId());
            int maxMemberCount = UnionConfigMgr.getMaxMemberCount(unionInfo.getExperience(), unionInfo.isCross(), crossServerCount);
            resultObj.put("maxMemberNum", maxMemberCount);
            resultObj.put("serverId", unionInfo.getServerId());

            JSONArray memberArr = new JSONArray();
            if (!unionInfo.isDelete()) {
                // 商会解散的情况下不再读取成员
                for (Map.Entry<Long, CrossUnionMember> memberEntry : CrossUnionMgr.getUnionMemberMap(unionUid).entrySet()) {
                    UserBaseInfo userBaseInfo = memberEntry.getValue().getUserBaseInfo();
                    if (userBaseInfo != null) {
                        JSONObject member = new JSONObject();
                        member.put("nickName", userBaseInfo.getNickName());
                        member.put("userId", memberEntry.getKey());
                        member.put("position", memberEntry.getValue().getPosition());
                        member.put("serverId", userBaseInfo.getServerId());
                        member.put("earnSpeed", userBaseInfo.getEarnSpeed());
                        member.put("vipLv", VipMgr.getVipLv(userBaseInfo.getVipExp()));
                        memberArr.add(member);
                    }
                }
            }
            resultObj.put("member", memberArr);
        }
        return resultObj.toJSONString();
    }

    public String queryMallCanBuy(int activityId, int mallId, long userId, long couponItemId) {
        JSONObject resultObj = new JSONObject();
        MallInfo mallInfo = MallMgr.getMallInfoByMallId(mallId);
        if(null == mallInfo){
            resultObj.put("ret", GameErrorCode.E_MALL_LIMIT_BUY);
            return resultObj.toJSONString();
        }
        if(couponItemId > 0){//使用优惠券
            GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
            if(null == player){
                resultObj.put("ret", GameErrorCode.E_PRE_CHARGE_PLAYER_OFFLINE);
                return resultObj.toJSONString();
            }
            UserCouponItem userCouponItem = player.getModule(CouponModule.class).getUserCouponItem(couponItemId);
            if(null == userCouponItem){
                resultObj.put("ret", GameErrorCode.E_COUPON_ITEM_NO_EXIST);
                return resultObj.toJSONString();
            }
            resultObj.put("couponGoodsId", userCouponItem.getGoodsId());
            if(userCouponItem.isUse()){
                resultObj.put("ret", GameErrorCode.E_COUPON_ITEM_HAS_USE);
                return resultObj.toJSONString();
            }
            if(System.currentTimeMillis() > userCouponItem.getExpirationTime()){
                resultObj.put("ret", GameErrorCode.E_COUPON_ITEM_OVER_TIME);
                return resultObj.toJSONString();
            }
            if(!GoodsMgr.isMallCanUseCouponItem(mallInfo, userCouponItem.getGoodsId())){
                resultObj.put("ret", GameErrorCode.E_COUPON_ITEM_MALL_CANNOT_USE);
                return resultObj.toJSONString();
            }
        }
        if(activityId > 0){
            ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(activityId);
            if (null != activityInfo) {
                if (activityInfo.getType() == eActivityType.RechargeActivity.getValue() &&
                        activityInfo.getChildType() == eActivityChargeType.GoldTokenCharge.getChildType()
                ) {//代金币礼包游戏内不能购买
                    resultObj.put("ret", GameErrorCode.E_PRE_CHARGE_ACTIVITY_NO_IN_TIME);
                    return resultObj.toJSONString();
                }
            }
            int ret = GamePublicFunction.activityMallCanBuy(activityId, mallId, userId).getRet();
            resultObj.put("ret", ret);
            return resultObj.toJSONString();
        }else {
            if(GameConfig.PRIVILEGE_WEEK_CARD_MALL_ID == mallId || GameConfig.SUBSCRIBE_WEEK_CARD_MALL_ID == mallId
                    || mallInfo.getCategory() == eMallCategory.PatronsFund.getValue()
            ){
                int ret = GamePublicFunction.normalMallCanBuy(mallId, userId);
                resultObj.put("ret", ret);
                return resultObj.toJSONString();
            }
            resultObj.put("ret", 0);
            return resultObj.toJSONString();
        }
    }

    public int queryRechargeSwitchOpen(long userId) {
        if (eChannelType.isXiaoChengxuChannel(ServerListMgr.getChannelId(GameServer.getInstance().getServerId()))) {
            // 小程序渠道 判断是否开启充值
            GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
            if (player == null) {
                return GameErrorCode.E_PRE_CHARGE_PLAYER_OFFLINE;
            }
            if (!RechargeSwitchConfigMgr.canPreCharge(player)) {
                return GameErrorCode.E_PRE_CHARGE_ACTIVITY_NO_IN_TIME;
            }
        }
        return 0;
    }

    public String getCanBuyProductList(long userId, String language, boolean isBackend) {
        JSONObject resultObj = new JSONObject();
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        UserInfo userInfo;
        if (null == player) {
            userInfo = UserMgr.getUserInfo(userId);
        } else {
            userInfo = player.getUserInfo();
        }
        if (null == userInfo) {
            resultObj.put("ret", 1);
            return resultObj.toJSONString();
        }
        language = LanguageType.platformLanguageMapping(language, userInfo.getLanguage());
        JSONObject dataObj = new JSONObject();
        JSONArray mallArray = new JSONArray();

        List<JSONObject> objList;
        if (0 < ChannelConfig.THIRD_PARTY_RECHARGE_MARK) {//元宝类、特权卡类
            //元宝
            objList = GamePublicFunction.getIngotsMall(userId, language, isBackend);
            mallArray.addAll(objList);
            //特权卡
            objList = GamePublicFunction.getLocalConfigMall(userId, eMallCategory.PrivilegeCard.getValue(), language);
            mallArray.addAll(objList);
            //通宝
            objList = GamePublicFunction.getLocalConfigMall(userId, eMallCategory.TongBaoRecharge.getValue(), language);
            mallArray.addAll(objList);
        }

        if (1 < ChannelConfig.THIRD_PARTY_RECHARGE_MARK) {//活动类礼包
            //基金
            objList = GamePublicFunction.getLocalConfigMall(userId, eMallCategory.Fund.getValue(), language);
            mallArray.addAll(objList);
            //密卷
            objList = GamePublicFunction.getLocalConfigMall(userId, eMallCategory.SecretVolume.getValue(), language);
            mallArray.addAll(objList);
            //战令冲榜礼包
            objList = GamePublicFunction.getLocalConfigMall(userId, eMallCategory.ZhanLingGiftBag.getValue(), language);
            mallArray.addAll(objList);
            //限时充值活动礼包
            objList = GamePublicFunction.getRechargeActivityMall(userId, language);
            mallArray.addAll(objList);

            //活动礼包
            objList = GamePublicFunction.getActivityMall(userId, language);
            mallArray.addAll(objList);
            //象棋大逃杀
          //  objList = GamePublicFunction.getChineseChessActivityMall(userId, language);
            //门客无双基金
            objList = GamePublicFunction.getLocalConfigMall(userId, eMallCategory.PatronsFund.getValue(), language);
            mallArray.addAll(objList);
        }

        dataObj.put("buyList", mallArray);
        resultObj.put("ret", 0);
        resultObj.put("data", dataObj);
        return resultObj.toJSONString();
    }

    public String getCanBuyProductListBackend(long userId, String language) {
        //后台批量第三方充值把用户加载出来查看可以购买的项目
        GamePlayer player = GamePlayerMgr.getPlayer(userId);
        return getCanBuyProductList(userId, language, true);
    }

    public int isProductCanBuy(long userId, int mallId) {
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        UserInfo userInfo;
        if (null == player) {
            userInfo = UserMgr.getUserInfo(userId);
        } else {
            userInfo = player.getUserInfo();
        }
        if (null == userInfo) {
            return GameErrorCode.E_USER_NO_FOUND;
        }
        MallInfo mallInfo = MallMgr.getMallInfoByMallId(mallId);
        if (null == mallInfo) {//商品信息找不到
            return GameErrorCode.E_MALL_NO_EXIST;
        }
        if (0 == ChannelConfig.THIRD_PARTY_RECHARGE_MARK) {//商品信息找不到，不开第三方充值
            return GameErrorCode.E_MALL_NO_EXIST;
        }
        if (mallInfo.getCategory() == eMallCategory.Ingots.getValue()) {//元宝
            return 0;
        } else if (mallInfo.getCategory() == eMallCategory.TongBaoRecharge.getValue()) {
            BaseRMBMallLimit baseRMBMallLimit = MallLimitFactory.getMallLimit(userId, mallInfo, null);
            if (null == baseRMBMallLimit) {
                return GameErrorCode.E_MALL_NO_EXIST;
            }
            return baseRMBMallLimit.checkMallLimit().getRet();
        } else if(MallMgr.isSubscribeMall(mallId)){
            return GameErrorCode.E_MALL_LIMIT_BUY;
        } else {//充值活动商品
            if (2 == ChannelConfig.THIRD_PARTY_RECHARGE_MARK || 3 == ChannelConfig.THIRD_PARTY_RECHARGE_MARK) {
                ActivityInfo activityInfo = null;
                if(mallInfo.getActivityId() > 0) {
                    activityInfo = NormalActivityMgr.getActivityInfo(mallInfo.getActivityId());
                    if(null == activityInfo){
                        activityInfo = RelationActivityMgr.getOpenActivityInfo(mallInfo.getActivityId());
                    }
                    if(null == activityInfo) {//不在活动时间
                        activityInfo = UnionWarActivityMgr.getOpenActivityInfo(mallInfo.getActivityId());
                    }
                }
                BaseRMBMallLimit baseRMBMallLimit = MallLimitFactory.getMallLimit(userId, mallInfo, activityInfo);
                if(null == baseRMBMallLimit){
                    return GameErrorCode.E_MALL_NO_EXIST;
                }else {
                    return baseRMBMallLimit.checkMallLimit().getRet();
                }
            } else {//商品信息找不到，不开第三方充值
                return GameErrorCode.E_MALL_NO_EXIST;
            }
        }
    }

    public int platformSendReward(long userId, int goodsId, int count, int type) {
        GoodsInfo goodsInfo = GoodsMgr.getGoodsById(goodsId);
        if (null == goodsInfo) {
            return GameErrorCode.E_GOODS_NO_EXIST;
        }
        if (eGoodsType.PlatformGoods.getValue() == goodsInfo.getType() &&
                0 == goodsInfo.getParamList().get(0).compareTo(BigInteger.ONE)) {
            return GameErrorCode.E_PLATFORM_GOODS_IS_LOCK;
        }
        String language = UserMgr.getLanguage(userId);
        String mailTitle;
        String mailContent;
        if(1 == type){
            String goodsName = ServerLanguageMgr.getContent(goodsInfo.getGoodsName(), language);
            mailTitle = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.PLATFORM_MAIL_GONGZHONGHAO_REWARD_TITLE, language), goodsName);
            mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.PLATFORM_MAIL_GONGZHONGHAO_REWARD_CONTENT, language), goodsName);
            MailManager.sendMail(userId, eMailType.GONGZHONGHAO.getValue(), PropertyHelper.parseGoodsToString(goodsId, BigInteger.valueOf(count)), mailContent, mailTitle);
        }else {
            mailTitle = ServerLanguageMgr.getContent(goodsInfo.getMailTitle(), language);
            mailContent = ServerLanguageMgr.getContent(goodsInfo.getMailContent(), language);
            if (StringUtils.isNullOrEmpty(mailTitle)) {
                mailTitle = MultipleLanguageMgr.getContent(MailManager.PLATFORM_MAIL_REWARD_TITLE, language);
            }
            if (StringUtils.isNullOrEmpty(mailContent)) {
                mailContent = MultipleLanguageMgr.getContent(MailManager.PLATFORM_MAIL_REWARD_CONTENT, language);
            }
            MailManager.sendMail(userId, eMailType.DAILY.getValue(), PropertyHelper.parseGoodsToString(goodsId, BigInteger.valueOf(count)), mailContent, mailTitle);
        }
        return 0;
    }

    public String queryPlayerOnline(String openIds) {
        List<String> openIdList = StringUtils.stringToStringList(openIds, ",");
        JSONObject resultObj = new JSONObject();
        Map<Long, GamePlayer> playerMap = GamePlayerMgr.getCopyPlayerMap();
        for (String openId : openIdList) {
            GamePlayer player = null;
            for (GamePlayer tempPlayer : playerMap.values()) {
                if (tempPlayer.getState() == PlayerState.ONLINE && Objects.equals(tempPlayer.getUserInfo().getOpenId(), openId)) {
                    player = tempPlayer;
                }
            }
            int online = 0;
            if (null != player) {
                online = 1;
            }
            resultObj.put(openId, online);
        }
        return resultObj.toJSONString();
    }

    /**
     * 触发平台行为（签到等）
     * @param type 1：论坛签到
     * @param platformUserId 玩家平台id
     * @param date 日期，如 20220706
     * @return
     */
    public void triggerPlatformUserBehavior(int type, String platformUserId, String date){
        ServerInfo serverInfo = ServerListMgr.getServerInfo(GameServer.getInstance().getServerId());
        if(PlatformUserIdMgr.openBehavior(type, serverInfo)){
            for (GamePlayer player : GamePlayerMgr.getAllOnlinePlayer()) {
                if(player.getUserInfo().getPlatformUserId().equals(platformUserId)){
                    if(type == 1) {
                        player.notifyListener(eGamePlayerEventType.LunTanLoginTimes.getValue(), 1);
                        break;
                    }else if(type == 3){
                        player.notifyListener(eGamePlayerEventType.ZfbIndexSetting.getValue(), 1);
                        break;
                    }
                }
            }
        }
    }

    /**
     * 触发平台条件达成，暴力达成，鉴别type是否有效
     */
    public int reachPlatformCondition(long userId, int type){
        try {
            GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
            if(player != null){
                return PlatformActivityMgr.reachCondition(player, type);
            }
            return PlatformActivityMgr.reachCondition(userId, type);
        }catch (Exception e){
            PlatformActivityMgr.getLogger().error("reachPlatformCondition error ", e);
            return 0;
        }
    }

    public boolean addUserBehavior(String uid, int type){
        int today = Integer.valueOf(DateHelper.getPyyyyMMddDateString(System.currentTimeMillis() / 1000));
        if(type == 3){
            today = type;
        }
        return PlatformUserBehaviorMgr.addUserBehavior(uid, type, today);
    }


    public boolean checkNameForbidden(String nickName) {
        return ForbiddenWordMgr.isNickNameForbidden(nickName);
    }

    /**
     * 角色名违规修改
     */
    public int changeUserNickName(long userId) {
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        UserInfo userInfo;
        if(null == player){
            userInfo = UserMgr.getUserInfo(userId);
        }else {
            userInfo = player.getUserInfo();
        }
        if (null == userInfo) {
            return GameErrorCode.E_PLAYER_NO_FOUND;
        }
        String name = NameMgr.getRandomName(eSexType.parse(userInfo.getSex()), userInfo.getLanguage());
        while (UserBussiness.isSameNickName(name) || ForbiddenWordMgr.isNickNameForbidden(name)) {
            name = NameMgr.getRandomName(eSexType.parse(userInfo.getSex()), userInfo.getLanguage());
        }
        if(null != player) {
            player.getModule(PlayerModule.class).setNickName(name);
        }else {
            userInfo.setNickName(name);
        }
        String reward = PropertyHelper.parsePropertyToString(new Property(GameConfig.GAME_ITEM_CHANGE_NAME, BigInteger.ONE));
        //发邮件
        String mailTitle = MultipleLanguageMgr.getContent(MailManager.USER_NAME_CHANGE_TITLE, userInfo.getLanguage());
        String mailContent = MultipleLanguageMgr.getContent(MailManager.USER_NAME_CHANGE_CONTENT, userInfo.getLanguage());
        MailManager.sendMail(userInfo.getUserId(), eMailType.SYSTEM.getValue(), reward, mailContent, mailTitle);
        //上报新的名称
        if(null != player) {
            ThirdPartyMgr.roleReport(userInfo, player.getIp());
        }else {
            ThirdPartyMgr.roleReport(userInfo, "114.114.114.114");
        }
        return 0;
    }

    /**
     * 工会名或者公告违规修改
     */
    public int changeUnion(String unionId, String type) {
        UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionId);
        if (unionInfo == null || unionInfo.isDelete()) {
            return GameErrorCode.E_UNION_NO_FOUND;
        }
        UserInfo masterUser = UserMgr.getUserInfo(unionInfo.getMasterUserId());
        if (ThirdPartyMgr.UnionNameType.equals(type)) {
            String unionName = masterUser.getNickName() + "商";
            int i = 2;
            while (UnionMgr.checkUnionNameSame(unionName)) {
                unionName = masterUser.getNickName() + "商" + i;
                i++;
            }
            unionInfo.setUnionName(unionName);
            MonopolyMarketMgr.changeUnionName(unionId,unionName);
            String reward = PropertyHelper.parsePropertyToString(new Property(GameConfig.GAME_MONEY_INGOTS, BigInteger.valueOf(GameConfig.UNION_CHANGE_NAME_COST)));
            //发邮件
            String mailTitle = MultipleLanguageMgr.getContent(MailManager.UNION_NAME_CHANGE_TITLE, masterUser.getLanguage());
            String mailContent = MultipleLanguageMgr.getContent(MailManager.UNION_NAME_CHANGE_CONTENT, masterUser.getLanguage());
            MailManager.sendMail(masterUser.getUserId(), eMailType.SYSTEM.getValue(), reward, mailContent, mailTitle);
            //上报新的公会名
//            ThirdPartyMgr.unionNameReport(unionId, unionName);
        } else if (ThirdPartyMgr.UnionNoticeType.equals(type)) {
            unionInfo.setOutNotice("");
            //发邮件
            String mailTitle = MultipleLanguageMgr.getContent(MailManager.UNION_NOTICE_CHANGE_TITLE, masterUser.getLanguage());
            String mailContent = MultipleLanguageMgr.getContent(MailManager.UNION_NOTICE_CHANGE_CONTENT, masterUser.getLanguage());
            MailManager.sendMail(masterUser.getUserId(), eMailType.SYSTEM.getValue(), "", mailContent, mailTitle);
        } else {
            return GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
        }

        return 0;
    }

    /**
     * 角色名上报
     */
    public int roleReport(String platformUserId, String userId, String nickName, String ip) {
        ThirdPartyMgr.roleReport(platformUserId, userId, nickName, ip);

        //创角
        DataAnalyticsMgr.createRole(platformUserId, userId, nickName, ip);
        try {
            PlatformMailAntiActivityMgr.sendMail(userId);
        }catch (Exception e){

        }
        return 0;
    }

    /**
     * 更新玩家平台用户编号
     */
    public void updateUserPlatformUserId(long userId, String platformUserId, String platformUserName) {
        UserInfo userInfo = UserMgr.getUserInfo(userId);
        if (null != userInfo) {
            userInfo.setPlatformUserId(platformUserId);
            userInfo.setPlatformUserName(platformUserName);
        }
    }

    public String queryUserByAliasId(long userAliasId) {
        UserInfo userInfo = UserMgr.getUserInfoByAliasId(userAliasId);
        if(null == userInfo) {
            userInfo = UserBussiness.getUserInfoListByAliasId(userAliasId);
        }
        if (null == userInfo) {
            return "";
        }
        JSONObject userObj = new JSONObject();
        try {
            userObj.put("roleLevel", userInfo.getTitleId() + "");
            userObj.put("roleName", userInfo.getNickName());
            userObj.put("roleId", userInfo.getUserId() + "");
            userObj.put("phonePlatform", userInfo.getPhonePlatform());
        } catch (Exception ex) {
            logger.error("异常 " + ex);
        }
        return userObj.toJSONString();
    }

    public String queryUserUpgradeTime(long userId, int titleId) {
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        Map<Integer, UserTitleUpgrade> userTitleUpgradeMap;
        UserInfo userInfo;
        if(null != player) {
            userInfo = player.getUserInfo();
            userTitleUpgradeMap = player.getModule(PlayerModule.class).getUserTitleUpgradeMap();
        }else {
            userInfo = UserMgr.getUserInfo(userId);
            userTitleUpgradeMap = UserTitleUpgradeBussiness.getUserTitleUpgradeMap(userId);
        }
        JSONObject dataObj = new JSONObject();
        if(null == userInfo){//角色不存在
            dataObj.put("result", 0);
            dataObj.put("msg", "role no exist");
            return dataObj.toJSONString();
        }
        if(titleId <= 0){
            dataObj.put("result", 0);
            dataObj.put("msg", "titleLv argument error");
            return dataObj.toJSONString();
        }
        if(titleId == 1){//注册即送
            dataObj.put("result", 1);
            dataObj.put("upgradeDays", 0);
            return dataObj.toJSONString();
        }else {
            if(titleId > userInfo.getTitleId()){//等级未达到
                dataObj.put("result", 0);
                dataObj.put("msg", "role titleLv not reached");
                return dataObj.toJSONString();
            }
            UserTitleUpgrade userTitleUpgrade = userTitleUpgradeMap.get(titleId);
            if(null == userTitleUpgrade){
                dataObj.put("result", 0);
                dataObj.put("msg", "role title upgradeTime no find");
                return dataObj.toJSONString();
            }
            ServerInfo serverInfo = ServerListMgr.getServerInfo(GameServer.getInstance().getServerId());
            if(null == serverInfo){
                dataObj.put("result", 0);
                dataObj.put("msg", "serverInfo no find");
                return dataObj.toJSONString();
            }
            int days = DateHelper.calc2DateTDOADays(new Date(serverInfo.getOpenTime() * 1000),
                    new Date(userTitleUpgrade.getUpgradeTime() * 1000));

            dataObj.put("result", 1);
            dataObj.put("upgradeDays", days);
            return dataObj.toJSONString();
        }
    }

    public String queryXiaoMianData(String param) {
        JSONObject resultObj = new JSONObject();
        JSONObject paramObj;
        try {
            paramObj = JSONObject.parseObject(param);
        }catch (Exception e){
            resultObj.put("state", 0);
            resultObj.put("msg", "param parse json error,argument error");
            return resultObj.toJSONString();
        }
        long userId = paramObj.getLong("userId");
        long queryTime = paramObj.getLong("time");

        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        UserInfo userInfo;
        UserXiaoMianData userXiaoMianData;
        UserCard userCard;
        if(null != player) {
            userInfo = player.getUserInfo();
            userCard = player.getModule(CardModule.class).getUserCard();
            userXiaoMianData = player.getModule(XiaoMianModule.class).getUserXiaoMianData();
        }else {
            userInfo = UserMgr.getUserInfo(userId);
            userCard = UserCardBussiness.getUserCard(userId);
            userXiaoMianData = XiaoMianBussiness.getUserXiaoMianData(userId);
            if(null == userXiaoMianData){
                userXiaoMianData = new UserXiaoMianData();
            } else {
                long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000;
                if(zeroTime > userXiaoMianData.getResetTime()) {
                    if(zeroTime > userXiaoMianData.getResetTime()) {
                        userXiaoMianData.resetValue();
                        userXiaoMianData.setResetTime(zeroTime);
                    }
                }
            }
        }
        if(null == userInfo){//角色不存在
            resultObj.put("state", 0);
            resultObj.put("msg", "role no exist");
            return resultObj.toJSONString();
        }
        JSONObject dataObj = new JSONObject();
        dataObj.put("role_id", "" + userInfo.getUserId());
        dataObj.put("role_name", userInfo.getNickName());
        String serverName = ServerListMgr.getServerName(GameServer.getInstance().getServerId(), userInfo.getLanguage());
        dataObj.put("server_name", serverName);
        dataObj.put("datetime", DateHelper.getCurrentDateTimeString("yyyy-MM-dd"));

        JSONArray taskArray = new JSONArray();
        taskArray.add(GamePublicFunction.parseXiaoMianTaskObj("门客提升", "doormen_upgrade", userXiaoMianData.getPatronsUpgradeTimes()));
        taskArray.add(GamePublicFunction.parseXiaoMianTaskObj("知己谈心", "bosomfriend", userXiaoMianData.getBeautyTrystTimes()));
        taskArray.add(GamePublicFunction.parseXiaoMianTaskObj("徒弟培养", "disciple_training", userXiaoMianData.getChildTrainTimes()));
        taskArray.add(GamePublicFunction.parseXiaoMianTaskObj("客栈烹饪", "inn_cooking", userXiaoMianData.getInnCookTimes()));
        taskArray.add(GamePublicFunction.parseXiaoMianTaskObj("徒弟联姻", "disciple_marriage", userXiaoMianData.getMarriageTimes()));
        taskArray.add(GamePublicFunction.parseXiaoMianTaskObj("宴会积分", "banquet_points", userXiaoMianData.getBanquetScore()));
        taskArray.add(GamePublicFunction.parseXiaoMianTaskObj("月卡购买", "had_monthCard", PrivilegeCardMgr.isGetCardReward(userCard, eCardType.MonthCard.getValue())));
        taskArray.add(GamePublicFunction.parseXiaoMianTaskObj("年卡购买", "had_yearCard", PrivilegeCardMgr.isGetCardReward(userCard, eCardType.YearCard.getValue())));
        taskArray.add(GamePublicFunction.parseXiaoMianTaskObj("医馆接诊", "medical_consultation", userXiaoMianData.getClinicReception()));
        taskArray.add(GamePublicFunction.parseXiaoMianTaskObj("酒肆叫号", "wineshop_callnumber", userXiaoMianData.getWineShopCallNumber()));

        dataObj.put("task_progress", taskArray);

        if(!DateHelper.isSameDay(queryTime, System.currentTimeMillis() / 1000)){
            resultObj.put("state", 0);
            resultObj.put("msg", "query time is over now day");
            return resultObj.toJSONString();
        }else {
            resultObj.put("state", 1);
            resultObj.put("msg", "success");
            resultObj.put("data", dataObj);
            return resultObj.toJSONString();
        }
    }

    /**
     * 平台查询日常任务进度
     * @param param
     * @return
     */
    public String queryDailyTaskProgress(String param) {
        return GamePublicFunction.doQueryDailyTaskProgress(param);
    }

    /**
    * 描述：通知扣除元宝
    * 作者：zrq
    * 时间：2022/3/25
    * 参数：
    单号
    * 返回值：
    **/
    public int notifyDeductIngots(String orderNo) {
        return DeductIngotsManager.msgNotifyDeductIngots(orderNo);
    }

    public int loginCheckGameServerMemory(long userId) {
        return GamePublicFunction.loginCheckGameServerMemory(userId);
    }

    /**
     * wmm
     * 2023/2/5
     * cmd 元数据信息
     */
    public String listCommandApi(){
        Map<Integer, CmdMetaInfo> metaInfoMap = CmdMetaInfoMgr.getMetaInfoMap();
        if(metaInfoMap == null || metaInfoMap.size() == 0){
            return "[]";
        }
        List<CmdMetaInfo> list = new ArrayList<>(metaInfoMap.values());
        return JSON.toJSONString(list);
    }

    public long queryServerOnline() {
        return GamePlayerMgr.getGamePlayerCount();
    }
    /**
     * 扣代币
     */
    public String reduceToken(String orderNo) {
        return ReduceItemManager.msgNotifyReduceItem(orderNo);
    }
}
